package com.kuang.service;

import com.alibaba.fastjson.JSON;
import com.kuang.pojo.Content;
import com.kuang.utils.HtmlParseUtil;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.TermQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 路嘉图
 * @date 2021年05月11日 16:25
 */
@Service
public class ContentServiceImpl {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private HtmlParseUtil parseUtil;

    /**
     *  爬取到的数据批量添加到es中
     * @return
     */
    public Boolean parse(String keyword) throws Exception{
        List<Content> contentList = parseUtil.parseJD(keyword);

        BulkRequest bulkRequest = new BulkRequest();

        //设置超时时间
        bulkRequest.timeout("2m");

        for (int i = 0; i < contentList.size(); i++) {
            System.out.println(contentList.get(i));
            bulkRequest.add(
                    new IndexRequest("jd_goods")
                    .source(JSON.toJSONString(contentList.get(i)), XContentType.JSON)
            );
        }

        BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
        return !bulkResponse.hasFailures();

    }

    /**
     *  分页查询
     * @param keyword   关键字
     * @param pageNo    页码
     * @param pageSize  页大小
     * @return
     */
    public List<Map<String,Object>> searchPage(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=0){
            pageNo = 1;
        }
        if(pageSize<=0){
            pageSize = 5;
        }

        //条件查询
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

        //分页
        searchSourceBuilder.from(pageNo);
        searchSourceBuilder.size(pageSize);

        //精准匹配
        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title", keyword);
        searchSourceBuilder.query(termQueryBuilder);
        //超时
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));

        //执行搜索
        searchRequest.source(searchSourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String,Object>> list = new ArrayList<>();

        //解析结果
        for (SearchHit hit : searchResponse.getHits()) {
            list.add(hit.getSourceAsMap());
        }
        return list;
    }

    /**
     *  高亮查询
     * @param keyword
     * @param pageNo
     * @param pageSize
     * @return
     */
    public List<Map<String,Object>> searchPageHighLight(String keyword,int pageNo,int pageSize) throws IOException {
        if(pageNo<=0){
            pageNo = 1;
        }
        if(pageSize<=0){
            pageSize = 5;
        }

        //条件查询
        SearchRequest searchRequest = new SearchRequest("jd_goods");
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        //分页
        sourceBuilder.from(pageNo);
        sourceBuilder.size(pageSize);


        //匹配
        TermQueryBuilder termQueryBuilder = new TermQueryBuilder("title",keyword);
        sourceBuilder.query(termQueryBuilder);

        //超时
        sourceBuilder.timeout(new TimeValue(60,TimeUnit.SECONDS));

        //高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("title");
        //多个高亮显示
        highlightBuilder.requireFieldMatch(false);

        highlightBuilder.preTags("<span style='color:red'>");
        highlightBuilder.postTags("</span>");
        sourceBuilder.highlighter(highlightBuilder);

        //搜索
        searchRequest.source(sourceBuilder);
        SearchResponse searchResponse = restHighLevelClient.search(searchRequest, RequestOptions.DEFAULT);

        List<Map<String,Object>> list = new ArrayList<>();

        //解析结果
        for (SearchHit hit : searchResponse.getHits()) {

            //解析高亮的字段
            Map<String, HighlightField> fields = hit.getHighlightFields();
            HighlightField title = fields.get("title");

            //原来的结果
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //解析高亮的字段 把原来的字段替换成我们高亮的字段即可！
            if(title != null){
                Text[] fragments = title.getFragments();
                String n_title = "";
                for (Text text : fragments) {
                    n_title += text;
                }
                //高亮字段替换成原来的字段
                sourceAsMap.put("title",n_title);
            }

            list.add(hit.getSourceAsMap());
        }
        return list;

    }


}
